package cn.wk.userdetails;

import cn.wk.domain.Permission;
import cn.wk.domain.VipUser;
import cn.wk.mapper.PermissionMapper;
import cn.wk.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //从数据库中查询
        VipUser vipUser = userMapper.selectByUsername(name);
        //判断用户是否存在
        if(vipUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //获取权限
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(vipUser.getId());
        //循环
        permissions.forEach(permission -> {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getExpression());
            authorities.add(grantedAuthority);
        });

        //把认证信息和权限封装进userdetail中返回
        User userDetails = new User(name, vipUser.getPassword(), authorities);

        return userDetails;
    }
}
